package com.health;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.health.tools.GlobalConts;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

/**
 * 版本更新
 */
@SuppressLint("HandlerLeak")
public class UpdateVersion {
	public ProgressDialog pBar;
	private Handler handler = new Handler();
	private Context context;
	// private Dialog dialog;
	// private int ii = 0;
	private int newVerCode = 0;
	private boolean successDownload = false, flag = false;
	private boolean isDownloadStart = false;
	private File mFile;
	private static String UPDATE_SAVENAME = "NationalPublicHealthNew.apk";
	private static String UPDATE_SAVENAME_JTYS = "NationalPublicHealthNewJTYS.apk";
	private static String UpdateUrl = GlobalConts.URL_POST_UPDATE; // port接口
	private String download;
//	private static String urlUpdate = "api/app/nova/version";
	private static String urlUpdate = "api/app/jtys/nova/version";
	private ProgressDialog progressDialog = null;
	private boolean setDialogFlag = false;

	private Handler handler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 1: {
					if (flag) {
						int verCode = getVerCode(context);
						System.out.println(newVerCode + " asdas " + verCode);
						if (newVerCode > verCode) {
							String verName = getVerName(context);
							StringBuffer sb = new StringBuffer();
							sb.append("当前版本:");
							sb.append(verName);
							/*
							 * sb.append(" Code:"); sb.append(verCode);
							 */
							sb.append(", 发现新版本");
							sb.append(", 是否更新?");
							Dialog dialog = new AlertDialog.Builder(context).setTitle("软件更新").setMessage(sb.toString())
									// 设置内容
									.setPositiveButton("更新", // 设置确定按钮
											new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog, int which) {
													if (Environment.getExternalStorageState()
															.equals(android.os.Environment.MEDIA_MOUNTED)) {
														progressDialog = new ProgressDialog(context);
														progressDialog.setTitle("正在下载");
														progressDialog.setMessage("请稍候...");
														progressDialog
																.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

														downFile(download);
													} else {
														Toast.makeText(context, "存储卡不存在，请插入存储卡。", Toast.LENGTH_SHORT)
																.show();
													}
												}
											})
									.create();

							// 显示对话框
							dialog.show();
						} else {
							if (setDialogFlag) {
								new AlertDialog.Builder(context).setMessage("已经是最新版本").setPositiveButton("确定", null)
										.create().show(); // 设置内容
							}

							// 显示对话框
						}
					}
					break;
				}
				}
			}
			super.handleMessage(msg);
		}
	};

	public UpdateVersion(Context ctx) {
		context = ctx;
		// 验证版本
		new myThread().start();

	}

	// 以下部自动升级使用
	// 取代码版本
	public static int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo("com.health", 0).versionCode;
		} catch (NameNotFoundException e) {

		}
		return verCode;
	}

	// 取版本号
	public static String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo("com.health", 0).versionName;
		} catch (NameNotFoundException e) {

		}
		return verName;
	}

	class myThread extends Thread {
		@Override
		public void run() {
			try {
				// {"infor":[{"downurl":"http://baidu.com","id":"1","versionCode":"1","versionName":"1.0"}],"msg":"操作成功","success":true}
				String rd = "";
				if (GlobalConts.TYPE_GJJBGGWS.equals(NovaApplication.getType())) {
					rd = urlUpdatePost("type=14&ptype=2", urlUpdate);
				} else if (GlobalConts.TYPE_JTYS.equals(NovaApplication.getType())) {
//					rd = urlUpdatePost("type=15&ptype=2", urlUpdate);
					rd = urlUpdatePost("type=jt_2&ptype=3", urlUpdate);//参数说明：type值为jt_1： 公卫PAD V1 V2   
																		//ptype值为3：PAD 
																		//jt_2 PAD V3
				}

				System.out.println("asdasd" + rd);
				if (rd.equals("404")) {
					// ii = 3;
				} else {
					JSONObject jsonObject = new JSONObject(rd.toString());
					JSONArray json_arr = jsonObject.getJSONArray("infor");

					String versionCode = json_arr.getJSONObject(0).getString("versionCode");
					newVerCode = Integer.parseInt(versionCode);
					download = json_arr.getJSONObject(0).getString("downurl");
				}
			} catch (Exception e) {
				flag = false;
			}
			flag = true;
			sendMsg(1);
			super.run();
		}
	}

	private void sendMsg(int flag) {
		Message msg = new Message();
		msg.what = flag;
		handler1.sendMessage(msg);
	}

	public void finish() {
		// TODO Auto-generated method stub
		try {
			if (!successDownload && isDownloadStart) {
				mFile.delete();
			}
		} catch (Exception e) {
			// Log.e("debug", e.toString());
			e.printStackTrace();
		}

	}

	@SuppressLint("ShowToast")
	void downFile(final String url) {
		try {
			progressDialog.show();
			new Thread() {
				public void run() {
					HttpClient client = new DefaultHttpClient();
					HttpGet get = new HttpGet(url);
					HttpResponse response;
					try {
						response = client.execute(get);
						HttpEntity entity = response.getEntity();
						long length = entity.getContentLength();
						InputStream is = entity.getContent();
						FileOutputStream fileOutputStream = null;
						if (is != null) {
							File file = null;
							if (GlobalConts.TYPE_GJJBGGWS.equals(NovaApplication.getType())) {
								file = new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME);
							} else if (GlobalConts.TYPE_JTYS.equals(NovaApplication.getType())) {
								file = new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME_JTYS);
							}
							if(file==null){return;}
							fileOutputStream = new FileOutputStream(file);
							byte[] buf = new byte[1024];

							int ch = -1;
							int count = 0;
							int percent = 0;
							while ((ch = is.read(buf)) != -1) {
								fileOutputStream.write(buf, 0, ch);
								count += ch;
								if (((int) (100 * count / length)) > percent) {
									percent = (int) (100 * count / length);
									progressDialog.setProgress(percent);
									if (percent == 100) {
										successDownload = true;
									}
								}
								if (length > 0) {
								}
							}
						}
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						down();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
						progressDialog.cancel();
						Toast.makeText(context, "更新程序下载失败，请重新尝试", 1).show();
					}
				}
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void down() {
		handler.post(new Runnable() {
			public void run() {
				// finish();
				progressDialog.cancel();
				update();
			}
		});
	}

	void update() {
		// 下载完成，点击安装
		Intent intent = new Intent(Intent.ACTION_VIEW);
		/*
		 * intent.setDataAndType(Uri.fromFile(new File(Environment
		 * .getExternalStorageDirectory(), UPDATE_SAVENAME)),
		 * "application/vnd.android.package-archive");
		 * context.startActivity(intent);
		 */
		File apkfile = null;
		if (GlobalConts.TYPE_GJJBGGWS.equals(NovaApplication.getType())) {
			apkfile = new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME);
		} else if (GlobalConts.TYPE_JTYS.equals(NovaApplication.getType())) {
			apkfile = new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME_JTYS);
		}
		if (!apkfile.exists()) {
			return;
		}

		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		context.startActivity(intent);
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	public String urlUpdatePost(String params, String surl) throws Exception {
		surl = UpdateUrl + surl;
		String returnCode = null;
		System.out.println(surl);
		try {
			byte[] data = params.getBytes();
			/*
			 * java.util.Random r = new java.util.Random(); String par = ""; for
			 * (int i = 0; i < 10; i++) { par += r.nextInt(); }
			 */
			URL url = new URL(surl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(30 * 1000);
			conn.setDoOutput(true);// 发送POST请求必须设置允许输出
			conn.setDoInput(true);
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
			outStream.write(data);// 以内容实体方式发送请求参数
			outStream.flush();
			outStream.close();
			// 请求成功
			if (conn.getResponseCode() == 200) {
				InputStream iStream = conn.getInputStream();
				returnCode = readStream(iStream);
			}

		} catch (IOException e) {
			returnCode = "404";
		}

		return returnCode;

	}

	// 获取输入流数据
	public String readStream(InputStream inStream) throws Exception {
		StringBuffer sb = new StringBuffer();
		String readLine;
		String r = null;
		BufferedReader responseReader;
		// 处理响应流，必须与服务器响应流输出的编码一致
		responseReader = new BufferedReader(new InputStreamReader(inStream, "UTF_8"));
		while ((readLine = responseReader.readLine()) != null) {
			// sb.append(readLine).append("\n");
			sb.append(readLine);// 不需要加换行
		}
		r = sb.toString();
		responseReader.close();
		return r;
	}

	public boolean isSetDialogFlag() {
		return setDialogFlag;
	}

	public void setSetDialogFlag(boolean setDialogFlag) {
		this.setDialogFlag = setDialogFlag;
	}

}
